/*
 * Copyright (C) 2013 SeekDeepWithin.com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package com.seekdeepwithin.Controls;

import com.seekdeepwithin.Data.*;
import com.seekdeepwithin.DataAccess.*;
import java.util.*;
import javafx.concurrent.*;
import javafx.event.*;
import javafx.scene.web.*;
import org.w3c.dom.*;

/**
 * Used for java script actions.
 */
public class JavaActions
{
   private final IWebEventHandler m_Handler;
   private final WebEngine m_Engine;

   /**
    * Creates a new link java script object.
    * @param handler Event handler.
    */
   public JavaActions (IWebEventHandler handler, WebEngine engine)
   {
      this.m_Handler = handler;
      this.m_Engine = engine;
   }

   public void openGlossary (String glossaryItem)
   {
      int a = 0;
   }

   public void openRead (String book, String subBook, String chapter, String verse)
   {
      int a = 0;
   }

   public void openSearch (String searchItem)
   {
      int a = 0;
   }

   public void openExternal (String link)
   {
      int a = 0;
   }

   /**
    * Opens an internal wiki link.
    * @param link ReadLink to open.
    */
   public void openLink (String link)
   {
      this.m_Handler.openLink (link);
   }

   /**
    * Opens an external wiki link.
    * @param link ReadLink to open.
    */
   public void openExternalLink (String link)
   {
      this.m_Handler.openExternalLink (link);
   }

   /**
    * Notifies the handler to copy the given data.
    * @param id Id of data being copied.
    * @param subBook Sub book data is in.
    * @param chapter Chapter data is in.
    * @param verse Verse number of the data being copied.
    */
   public void Copy (String id, String subBook, String chapter, String verse)
   {
      this.m_Handler.copy (subBook, chapter, verse);
   }

   /**
    * Show the TSK data for the given item.
    * @param id Id of data requesting TSK.
    * @param subBook Sub book data is in.
    * @param chapter Chapter data is in.
    * @param verse Verse number of the data being copied.
    */
   public void ShowTsk (String id, String subBook, String chapter, String verse)
   {
      /*
       try (Sqlite db = new Sqlite (MainController.getTskPath ()))
       {
       subBook = URLDecoder.decode (subBook, "UTF-8");
       chapter = URLDecoder.decode (chapter, "UTF-8");
       db.prepare ("SELECT * FROM Data NATURAL JOIN SubBooks WHERE SubBooks.BookName='" + subBook + "' AND Data.Chapter='" + chapter + "' AND Data.Verse='" + verse + "' ORDER BY Data.SortOrder;");
       db.start ();
       this.m_Engine.executeScript ("$('#m" + id + "').attr('refShown', 'true');");
       db.join ();
       StringBuilder html = new StringBuilder ();
       if (db.getResultCount () == 0)
       {
       html.append ("<p style=\"font-size:smaller;margin:0px;padding:0px;text-align:center;\">No references found.</p>");
       }
       else
       {
       int i = 0;
       boolean handled = false;
       int wordIndex = db.getColumnIndex ("Word");
       int refListIndex = db.getColumnIndex ("RefList");
       if (db.getResultCount () == 1)
       {
       List<String> data = db.getRow (0);
       String word = data.get (wordIndex);
       if (word.split ("\\s").length > 5)
       {
       StringBuffer result = new StringBuffer ();
       String refList = data.get (refListIndex);
       Pattern p = Pattern.compile ("([\\w\\s:,-]+)");
       Matcher m = p.matcher (refList);
       while (m.find ())
       {
       m.appendReplacement (result, "<a href=\"#\" id=\"0" + id + i +
       "\" onclick=\"app.TskToolTip (this)\">" + m.group (1) + "</a>");
       i++;
       }
       m.appendTail (result);
       html.append ("<p style=\"font-size:smaller;margin:0px;padding:0px;text-align:center;\">")
       .append (result)
       .append ("</p>");
       handled = true;
       }
       }
       if (!handled)
       {
       html.append ("<dl class=\"tsk\">");
       for (int a = 0; a < db.getResultCount (); a++)
       {
       List<String> data = db.getRow (a);
       html.append ("<dt>")
       .append (data.get (wordIndex))
       .append ("</dt>")
       .append ("<dd>");
       StringBuffer result = new StringBuffer ();
       String refList = data.get (refListIndex);
       Pattern p = Pattern.compile ("([\\w\\s:,-]+)");
       Matcher m = p.matcher (refList);
       while (m.find ())
       {
       m.appendReplacement (result, "<a href=\"#\" id=\"" + a + id + i +
       "\" onclick=\"app.TskToolTip (this)\">" + m.group (1) + "</a>");
       i++;
       }
       m.appendTail (result);
       html.append (result)
       .append ("</dd>");
       }
       html.append ("</dl>");
       }
       }
       String append = html.toString ().replaceAll ("'", "\\\\'");
       this.m_Engine.executeScript ("$('#p_" + id + "').append('" + append + "');");
       this.m_Engine.executeScript ("$(\"a\").click(function(event){event.preventDefault();});");
       }
       catch (SQLiteException | InterruptedException | IOException ex)
       {
       MessageBox.show (null, ex.getMessage (), "Reference Error - WebControl.ShowTsk", MessageBox.ICON_ERROR | MessageBox.OK);
       }*/
      // TODO: Change show to hide on options.
   }

   public void ShowOptions (String id, String subBook, String chapter, String verse, String showReferences)
   {
      String val = (String) this.m_Engine.executeScript ("$('#m" + id + "').attr('refShown');");
      this.m_Engine.executeScript ("$('#m" + id + "').removeData('qtip');");
      StringBuilder script = new StringBuilder ();
      script.append ("$('#m").append (id).append ("').qtip({").append ("content:{text:'<div id=\"contextMenu\"><ul>").append ("<li><a href=\"#\" id=\"copy").append (id).append ("\" onclick=\"app.Copy (\\'").append (id).append ("\\', \\'").append (subBook).append ("\\', \\'").append (chapter).append ("\\', \\'").append (verse).append ("\\');\">Copy</a></li>");
      if (showReferences.isEmpty () && !val.equals ("true")) {
         script.append ("<li><a href=\"#\" id=\"ref").append (id).append ("\" onclick=\"app.ShowTsk (\\'").append (id).append ("\\', \\'").append (subBook).append ("\\', \\'").append (chapter).append ("\\', \\'").append (verse).append ("\\')\">Show References</a></li>");
      }
      script.append ("</ul></div>',").append ("title:{text:'Options'}},").append ("show:{event:false,ready:true},").append ("effect: function() { $(this).show('slide', null, 100); },").append ("position:{my:'top left',at:'bottom left',viewport:$(window)},").append ("events: {show: function(event, api) {").append ("$(\"a\").click(function(evnt){evnt.preventDefault();});}},").append ("hide:{event:'click unfocus',fixed:true},").append ("style:{classes: 'ui-tooltip-shadow ui-tooltip-light'}").append ("});");
      this.m_Engine.executeScript (script.toString ());
   }

   public void TskToolTip (Object item)
   {
      Element link = (Element) item;
      final String passage = link.getTextContent ();
      final String id = link.getAttributeNode ("id").getValue ();
      StringBuilder script = new StringBuilder ();
      script.append ("$('#").append (id).append ("').qtip({").append ("content:{text:'Loading...',").append ("title:{text:'").append (passage).append ("'}},").append ("show:{event:false,ready:true},").append ("position:{my:'top center',at:'bottom center'},").append ("hide:{event:'unfocus'},").append ("style:{classes: 'ui-tooltip-shadow ui-tooltip-tipped'}").append ("});");
      this.m_Engine.executeScript (script.toString ());
      ArrayList<ReadLink> passageList = Parser.Parse (passage);
      PassageFinderService service = new PassageFinderService ();
      service.setLinkList (passageList);
      service.setOnSucceeded (new EventHandler<WorkerStateEvent> ()
      {
         @Override
         public void handle (WorkerStateEvent event)
         {
            PassageFinderService searchService = (PassageFinderService) event.getSource ();
            m_Engine.executeScript ("$('#m" + id + "').qtip('hide');");
            m_Engine.executeScript ("$('#m" + id + "').removeData('qtip');");
            StringBuilder script = new StringBuilder ();
            script.append ("$('#").append (id).append ("').qtip({").append ("content:{text:'").append (searchService.getValue ().replaceAll ("'", "\\\\'")).append ("',").append ("title:{text:'").append (passage).append ("'}},").append ("show:{event:false,ready:true},").append ("position:{my:'top center',at:'bottom center',viewport:$(window)},").append ("hide:{event:'unfocus'},").append ("style:{classes: 'ui-tooltip-shadow ui-tooltip-tipped'}").append ("});");
            m_Engine.executeScript (script.toString ());
         }
      });
      service.start ();
   }

   /**
    * Selects the give data.
    * @param id Id of data to select.
    */
   public void Select (Object item, String id)
   {
      Element link = (Element) item;
      String selected = link.getAttribute ("isSelected");
      if (selected == null || selected.isEmpty ()) {
         link.setAttribute ("isSelected", "true");
         this.m_Engine.executeScript ("$('#td_l" + id + "').css (\"background-color\", \"#CCE3F4\");");
         this.m_Engine.executeScript ("$('#td_r" + id + "').css (\"background-color\", \"#CCE3F4\");");
         this.m_Engine.executeScript ("$('#p_" + id + "').css (\"background-color\", \"#CCE3F4\");");
      } else {
         link.removeAttribute ("isSelected");
         this.m_Engine.executeScript ("$('#td_l" + id + "').css (\"background-color\", \"\");");
         this.m_Engine.executeScript ("$('#td_r" + id + "').css (\"background-color\", \"\");");
         this.m_Engine.executeScript ("$('#p_" + id + "').css (\"background-color\", \"\");");
      }
      // TODO: Change select to deselect.
   }
}
